<template>
  <div>
  <van-nav-bar
            title="修改地址"
            left-text="返回"
            left-arrow
            @click-left="$router.go(-1)"
            />

            
        <el-form v-model="editItem">
            <el-form-item label="姓名">
                <el-input v-model="editItem.name"></el-input>
            </el-form-item>
            <el-form-item label="电话">
                <el-input v-model="editItem.phone"></el-input>
            </el-form-item>
            <el-form-item label="城市">
                <el-input v-model="editItem.city" :readonly="true"></el-input>
            </el-form-item>
            <el-form-item label="详细地址">
                <el-input v-model="editItem.desc"></el-input>
            </el-form-item>
            <el-form-item label="状态">
                <el-input v-model="editItem.state"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button style="width: 100%;" type="primary" @click="edit">保存</el-button>
            </el-form-item>
        </el-form>
       
        <div id="container">
            <input v-model="keyword" id="keyword" placeholder="请输入搜索位置" autocomplete="off" @keyup.enter="searchPlace" />
    <button @click="searchPlace">搜索</button>
    <div>
      <p>经度: {{ longitude }}</p>
      <p>纬度: {{ latitude }}</p>
      <p>{{ message }}</p>
        </div> 
    <div v-if="places.length" class="ban">
      <h3>搜索结果:</h3>
      <ul>
        <!-- @vue-ignore -->                                                   
        <li v-for="place in places" :key="place.id" @click="selectPlace(place)">
          <!-- @vue-ignore -->
          {{ place.name }}</li>
           
        
      </ul>
    </div>
  </div>
  </div>
</template>

<script setup lang="ts">
import {ref,onMounted} from "vue"
import {useRoute,useRouter} from 'vue-router';
import axios from "axios"
import AMapLoader from '@amap/amap-jsapi-loader';
import * as AMap from '@amap/amap-jsapi-loader';
const router=useRouter()
const route = useRoute();
const searchResult = ref<any>([]);
const id=route.query.id;
console.log(id)
interface Place {
  id: string;
  name: string;
  location: string;
  addressComponent: {
    city: string;
  };
}
const editItem=ref<any>({
    id:'',
    name:'',
    phone:'',
    city:'',
    desc:"",
    state:""
})


onMounted(async()=>{
    console.log(route.query)
    editItem.value.id = route.query.id;
    editItem.value.name = route.query.addresname;
    editItem.value.phone = route.query.addresphone;
    editItem.value.city = route.query.addrescity;
    editItem.value.desc = route.query.addresdesc;
    editItem.value.state = route.query.addresstate;
})

const edit=async()=>{
  console.log(editItem.value);
 await axios.post('/api/address/update',editItem.value).then((res) =>{
    console.log(res);
    router.push('/address')
  })
 
}


const props = defineProps({
  message: String
})

const keyword = ref('')
const longitude = ref(null)
const latitude = ref(null)
const places = ref([]) // 存储搜索结果
const emit = defineEmits(['update:longitude', 'update:latitude', 'update:address', 'childEvent'])
let map:any
let marker:any// 定义标记变量

const initMap = () => {
  AMapLoader.load({
    key: '10a926dc02f8811c879049c06b78031a',
    version: '1.4.15',
    plugins: ['AMap.Autocomplete', 'AMap.PlaceSearch', 'AMap.Geocoder']
  }).then((AMap) => {
    map = new AMap.Map('container', {
      resizeEnable: true,
      zoom: 10,
      center: [116.397428, 39.90923]
    })
    emit('childEvent', 'Hello from Child!')

    map.on('click', async (e:any) => {
      longitude.value = e.lnglat.lng
      latitude.value = e.lnglat.lat
      emit('update:longitude', longitude.value)
      emit('update:latitude', latitude.value)

      const apiKey = '10a926dc02f8811c879049c06b78031a'
      const url = `https://restapi.amap.com/v3/geocode/regeo?key=${apiKey}&location=${longitude.value},${latitude.value}`
      try {
        const response = await fetch(url)
        const data = await response.json()

        if (data.status === '1') {
          const address = data.regeocode.formatted_address
          emit('update:address', address)
        }
      } catch (error) {
        console.error('请求错误:', error)
      }
    })
  }).catch((error) => {
    console.error('加载 AMap 失败:', error)
  })
}

// 搜索地点
const searchPlace = async () => {
  const apiKey = '10a926dc02f8811c879049c06b78031a'
  const url = `https://restapi.amap.com/v3/place/text?keywords=${encodeURIComponent(keyword.value)}&key=${apiKey}&extensions=all`
  
  try {
    const response = await fetch(url)
    const data = await response.json()
    if (data.status === '1') {
      places.value = data.pois // 存储搜索结果
    } else {
      console.error('搜索失败:', data.info)
      places.value = []
      
    }
  } catch (error) {
    console.error('请求错误:', error)
  }
}

const selectPlace = (place:any) => {
  longitude.value = place.location.split(',')[0]
  latitude.value = place.location.split(',')[1]

  // 提取城市信息并更新到 editItem 的 city 字段
  if (place.addressComponent && place.addressComponent.city) {
    editItem.value.city = place.addressComponent.city;
  } else {
    console.error('城市信息未找到');
  }

  // 更新详细地址字段
  editItem.value.desc = place.name; // 假设 place.name 包含详细地址信息

  // 在地图上添加标记
  if (marker) {
    marker.setMap(null);
  }
  // @ts-ignore
  marker = new AMap.Marker({
    position: [longitude.value, latitude.value],
    title: place.name
  });
  marker.setMap(map);
   // 设置地图中心点
  map.setCenter([longitude.value, latitude.value]);
   // 清空搜索结果
 places.value = [];
  console.log(`选择地点: ${place.name}, 经度: ${longitude.value}, 纬度: ${latitude.value}`);
}


// 在组件挂载后初始化地图
onMounted(initMap)


</script>

<style lang="scss" scoped>
 #container {
  padding: 0;
  margin: 0;
  width: 100%;
  height: 376px;
  
}

#keyword {
  margin-top: 1%;
  height: 30px;
  position: absolute;
   z-index: 99;
  
}
.ban{
 z-index: 99999;
 position: relative;
 background: #ffff;
 top: 30px;
}


#map-container {
  position: relative;
  width: 100%;
  height: 100%;
}

#map {
  width: 100%;
  height: 100%;
}
</style>